﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Windows;
using System.Windows.Controls;
using Model.Interfaces;
using View.EventArguments;
using View.Interfaces;
using View.Login;


namespace View
{
    public partial class MainWindow : IMainWindow
    {
        private bool _closing = false, confirmExitPanelShown = false, closeConfirm = true;
        private const string properties = "prop.ini";

        public event EventHandler<TryLoginEventAgrs> TryLoginEvent;
        public event EventHandler CallHelpEvent;

        public static IDictionary<string, string> ReadDictionaryFile(string fileName)
        {
            Dictionary<string, string> dictionary = new Dictionary<string, string>();
            foreach (string line in File.ReadAllLines(fileName))
            {
                if ((!string.IsNullOrEmpty(line)) &&
                    (!line.StartsWith(";")) &&
                    (!line.StartsWith("#")) &&
                    (!line.StartsWith("'")) &&
                    (line.Contains("=")))
                {
                    int index = line.IndexOf('=');
                    string key = line.Substring(0, index).Trim();
                    string value = line.Substring(index + 1).Trim();

                    if ((value.StartsWith("\"") && value.EndsWith("\"")) ||
                        (value.StartsWith("'") && value.EndsWith("'")))
                    {
                        value = value.Substring(1, value.Length - 2);
                    }
                    dictionary.Add(key, value);
                }
            }

            return dictionary;
        }

        public MainWindow()
        {
            InitializeComponent();
            this.WindowStartupLocation = System.Windows.WindowStartupLocation.CenterScreen;
            _closing = false;
            try
            {
                IDictionary<string, string> props = ReadDictionaryFile(properties);
                if (!Boolean.Parse(props["ConfirmClosing"]))
                {
                    _closing = true;
                    closeConfirm = true;
                }
            }
            catch (Exception e)
            {
                MessageBox.Show("Ошибка чтения конфигурационного файла!\n" + e.ToString());
            }
        }



        public void ShowLoginPanel()
        {
            var userLoginControl = new UserLoginControl();
            ((Grid)Content).Children.Clear();
            ((Grid)Content).Children.Add(userLoginControl);
            // <UserLoginControlListeners>
            userLoginControl.TryLoginEvent += TryLoginEventHandler;
            userLoginControl.CallHelpEvent += CallHelpEventHandler;
            // </UserLoginControlListeners>
        }

        public void ShowMainWorkSpace()
        {
            ((Grid)Content).Children.Clear();
            ((Grid)Content).Children.Add(new MainWorkspace());
        }

        private void CallHelpEventHandler(object sender, EventArgs e)
        {
            MessageBox.Show("MainWindow: CallHelpEvent!!!");
        }

        private void TryLoginEventHandler(object sender, TryLoginEventAgrs e)
        {
            if (TryLoginEvent != null)
                TryLoginEvent(this, e);
        }

/*        private void WindowClosing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            var result = MessageBox.Show("Действительно выйти?", "", MessageBoxButton.YesNo);
            e.Cancel = (result == MessageBoxResult.No);
        }
*/
        private void WindowClosing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            if (!_closing)
            {
                e.Cancel = true;
                if (!confirmExitPanelShown)
                {
                    try
                    {
                        confirmExitPanelShown = true;
                        var comfirmExitPanel = new PowerOffPanel {Margin = new Thickness(0)};
                        ((Grid) Content).Children.Add(comfirmExitPanel);
                        comfirmExitPanel.CancelExitEvent += delegate
                                                                {
                                                                    ((Grid) Content).Children.Remove(comfirmExitPanel);
                                                                    confirmExitPanelShown = false;
                                                                };

                        comfirmExitPanel.OkExitEvent += delegate
                                                            {
                                                                _closing = true;
                                                                if (comfirmExitPanel.dontshow.IsChecked.Value)
                                                                {
                                                                    File.WriteAllText(properties, "ConfirmClosing=false");
                                                                }
                                                                Close();
                                                            };
                    }
                    catch(Exception exception)
                    {
                        MessageBox.Show(exception.ToString());
                    }
                }
            }
            else e.Cancel = false;
        }

        public void ShowMessageLoginFail()
        {
          //  ((UserLoginControl)((Grid)Content).Children[0]).ShowMessageLoginFail();
        }
    }
}